<?php





namespace app\admin\controller;



use app\data\controller\store\GoodsCate;

use app\data\model\GoodsAttribute;

use app\data\model\GoodsAttributeValue;

use app\data\model\GoodsCate as ModelGoodsCate;

use app\data\model\ShopGoodsCate;

use app\data\model\StoreGoods;

use think\admin\Controller;

use think\admin\service\AdminService;

use think\admin\service\ModuleService;

use think\admin\service\SystemService;

use think\admin\storage\AliossStorage;

use think\admin\storage\QiniuStorage;

use think\admin\storage\TxcosStorage;

use think\admin\helper\QueryHelper;

use think\exception\HttpResponseException;
use think\facade\Db;
use think\facade\Request;



/**

 * 商品属性配置

 * Class Config

 * @package app\admin\controller

 */

class Attribute extends Controller

{

      /**

     * @auth true

     * @menu true

     */

    public function index(){

        $search = input('get.');
        $this->cate_list = ModelGoodsCate::where('status',1)->where('parent_id',0)->select();
        $parent_cate = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>0,'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
        foreach ($parent_cate AS $key => $value){
            //二级分类列表
            $parent_cate[$key]['child_cate_2'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$value['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            foreach ($parent_cate[$key]['child_cate_2'] AS $k => $val){
                //三级分类列表
                $parent_cate[$key]['child_cate_2'][$k]['child_cate_3'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$val['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            }
        }
        $this->parent_cate = $parent_cate;
        GoodsAttribute::mQuery()->with(['values','cates'])->layTable(function () {

            $this->title = '商品属性列表';

        }, function (QueryHelper $query) use ($search) {

            // 数据列表搜索过滤

            $query->like('name')->equal('cate_id');
            if(isset($search['types']) && $search['types'] != ''){

                $query->where('type',$search['types']);

            }

        });

    }





      /**

     * @auth true

     * @menu true

     */

    public function add(Request $request)

    {

        $this->title = '添加';
        if(request()->isPost()){
            $this->_vali([
                'name.require' => '名称不得为空',
                'cate_id.require'  => '分类不得为空',
            ]);
        }
        $this->cate_list = ModelGoodsCate::where('status',1)->where('parent_id',0)->select();
        $parent_cate = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>0,'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
        foreach ($parent_cate AS $key => $value){
            //二级分类列表
            $parent_cate[$key]['child_cate_2'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$value['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            foreach ($parent_cate[$key]['child_cate_2'] AS $k => $val){
                //三级分类列表
                $parent_cate[$key]['child_cate_2'][$k]['child_cate_3'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$val['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            }
        }
        $this->parent_cate = $parent_cate;
        $this->_form('goods_attribute','form');

    }



      /**

     * @auth true

     * @menu true

     */

    public function edit()

    {

        $this->title = '编辑';
        if(request()->isPost()){
            $this->_vali([
                'name.require' => '名称不得为空',
                'cate_id.require'  => '分类不得为空',
            ]);
        }

        $this->cate_list = ModelGoodsCate::where('status',1)->where('parent_id',0)->select();
        $parent_cate = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>0,'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
        foreach ($parent_cate AS $key => $value){
            //二级分类列表
            $parent_cate[$key]['child_cate_2'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$value['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            foreach ($parent_cate[$key]['child_cate_2'] AS $k => $val){
                //三级分类列表
                $parent_cate[$key]['child_cate_2'][$k]['child_cate_3'] = Db::name('StoreGoodsCate')->field('id,parent_id,title')->where(['parent_id'=>$val['id'],'is_deleted'=>0])->order('sort asc,id asc')->select()->toArray();
            }
        }
        $this->parent_cate = $parent_cate;
        // MyModel::mForm('form');

        $this->_form('goods_attribute','form');

    }





      /**

     * @auth true

     * @menu true

     */

    public function remove()

    {

        $this->_delete('goods_attribute');

    }



    protected function _form_filter(array &$data){

        if(isset($data['id'])){

            $data['values'] = GoodsAttributeValue::where('attribute_id',$data['id'])->select();

        }

    

    }



    protected function _form_result(bool $result,array &$data){

       

        if ($this->request->isPost()) try {

            if (empty($data['name'])) $this->error('属性名称不能为空！');

            if (empty($data['type'])) $this->error('类型不能为空！');

            if($data['type'] == 'select' || $data['type'] == 'checkbox'){

                if(empty($data['options']) || !is_array($data['options']) || count($data['options']) <=1){  

                    $this->error('请添加选项！');

                }

            }

            // 如果是下拉框类型，添加下拉选项

            if ($data['type'] === 'select' && !empty($data['options'])) {

                if( GoodsAttributeValue::where('attribute_id',$data['id'])->count()){

                    GoodsAttributeValue::where('attribute_id',$data['id'])->delete();

                }

                foreach ($data['options'] as $option) {

                    $attributeValue = new GoodsAttributeValue();

                    $attributeValue->attribute_id = $data['id'];

                    $attributeValue->value = $option;

                    $attributeValue->save();

                }

            }


            if ($data['type'] === 'checkbox' && !empty($data['options'])) {

                if( GoodsAttributeValue::where('attribute_id',$data['id'])->count()){

                    GoodsAttributeValue::where('attribute_id',$data['id'])->delete();

                }

                foreach ($data['options'] as $option) {

                    $attributeValue = new GoodsAttributeValue();

                    $attributeValue->attribute_id = $data['id'];

                    $attributeValue->value = $option;

                    $attributeValue->save();

                }

            }

            if($data['type'] === 'input'){

                if( GoodsAttributeValue::where('attribute_id',$data['id'])->count()){

                    GoodsAttributeValue::where('attribute_id',$data['id'])->delete();

                }

            }

        } catch (HttpResponseException $exception) {

            throw $exception;

        } catch (\Exception $exception) {

            return $this->error($exception->getMessage());

        }

    }

    //导入属性选项
    public function  upload_option(){
        if(empty($_FILES['file'])) return $this->error('请选择文件');
        $list = $this->big_csv_to_array($_FILES['file']['tmp_name']);
        $result = [];
        if(count($list)){
            foreach($list as $k=>$v){
                if($k == 0) continue;
                if(!$v[0] || empty($v)) continue;
                $result[] = $v[0];
            }
        }
        return $this->success($result);
    }

    private function big_csv_to_array($csv) {
        function big_csv_read($csv) {
            $handle = fopen($csv, 'rb');
    
            while (!feof($handle)) {
                yield fgetcsv($handle);
            }
            fclose($handle);
        }
        $result = big_csv_read($csv);
        
        $data = [];
        $i = 0;
        foreach($result as $row) {
          if($row) foreach ($row as &$value) {     
                $value = iconv('GBK', 'UTF-8', $value);
            }
     
            $data[] = $row;
        }
        return $data;
    }
}